<template>
  <div v-loading="loading">
    <el-row>
      <el-col style="text-align:left">
        <el-button
          type="success"
          @click="addBtnClick"
        >添加补卡记录</el-button>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.isNew ? '添加补卡记录':'添加补卡记录'"
      top="5vh"
      width="70%"
    >
      <el-scrollbar max-height="70vh">
        <el-form
          :model="dialogDatas.currentData"
          ref="dialogFrom"
          :rules="dialogDatas.formRules"
          label-position="top"
        >
          <el-form-item
            v-for="item in dialogDatas.formItems"
            :label="item.label"
            :prop="item.value"
          >

            <el-date-picker
              v-if="item.isDate"
              :disabled="(item.isEnableChange ? (dialogDatas.isNew ? false:true) : false) ||item.isDisabled"
              v-model="dialogDatas.currentData[item.value]"
              :type="item.dateOption ? item.dateOption.type : 'date'"
              :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
              :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
              :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
              :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
              :disabled-date="item.checkDisabledDate"
            />

            <!-- <el-select
              v-model="dialogDatas.currentData[item.value]"
              v-else-if="item.isSelect"
              style="width:100%"
              filterable
              :disabled="item.isDisabled"
            >
              <el-option
                v-for="item in dialogDatas.formOptions[item.value]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> -->

            <el-autocomplete
              v-else-if="item.value == 'RECLOCK_REASON'"
              v-model="dialogDatas.currentData[item.value]"
              :fetch-suggestions="item.handleGameSearch"
              clearable
            />

            <el-input
              v-else
              :disabled="item.isDisabled"
              v-model="dialogDatas.currentData[item.value]"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <!-- <el-button
            type="success"
            @click="dialogDatas.confirmBtnClick(0)"
          >
            保存
          </el-button> -->
          <el-button
            type="primary"
            @click="dialogDatas.confirmBtnClick(1)"
          >
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-table
      class="marginTop10"
      :data="tableDatas.tableDatasAfterPage"
      stripe
      border
      empty-text="无数据"
    >
      <el-table-column
        v-for="column in tableDatas.tableColumns"
        :prop="column.prop"
        :label="column.label"
        :align="column.align"
        :width="column.width"
      >
        <template
          #default="scope"
          v-if="column.prop =='operate'"
        >
          <!-- 新建 或 审批未通过 状态可以修改或删除 -->
          <div v-show="[0,3].includes(scope.row.STATE) && scope.row.CREATER_ID == userid">
            <el-button
              type="success"
              @click="tableDatas.editBtnClick(scope.row)"
            >修改</el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="确定删除该条记录?"
              @confirm="tableDatas.deleteBtnClick(scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
          <div v-show="[1].includes(scope.row.STATE) && scope.row.CHECK_ID == userid">
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              title="确定审批通过?"
              @confirm="tableDatas.checkBtnClick(scope.row)"
            >
              <template #reference>
                <el-button type="success">通过</el-button>
              </template>
            </el-popconfirm>
            <el-button
              type="danger"
              @click="tableDatas.returnBtnClick(scope.row)"
            >退回</el-button>
          </div>
        </template>
        <template
          #default="scope"
          v-if="column.prop =='STATE'"
        >

          <el-tag :type="dialogDatas.formOptions.STATE[scope.row['STATE']].type">
            {{ dialogDatas.formOptions.STATE[scope.row['STATE']].text }}
          </el-tag>

        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination>

  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';
import VueCookie from 'vue-cookie';
import store from '@/store';

import myAxios from '@/myAxios/myAxios';
import apiConfig from '@/myAxios/api.config';
import { dayjs } from 'element-plus';

export default {
  name: 'NewOrEditView',
  setup () {
    let userid = VueCookie.get('userid');

    let loading = ref(false);
    let departmentOptions = store.state.departmentOptions;

    let addBtnClick = function () {
      showFormDialog();
    };

    let showFormDialog = function (row) {
      if (row) {
        dialogDatas.isNew = false;
        dialogDatas.currentData = { ...row };
      }
      else {
        dialogDatas.isNew = true;
        dialogDatas.currentData = { ...dialogDatas.oriData };
      }
      dialogDatas.dialogFormVisible = true;
    };

    let dialogFrom = ref();
    let dialogDatas = reactive({
      dialogFormVisible: false,
      oriData: {
        CREATER_ID: userid,
        RECLOCK_DATE: '',
        RECLOCK_REASON: '',
        CHECK_ID: '',
        RETURN_REASON: '',
        SP_WORKID: '',
        SP_NAME: '',
      },
      currentData: {},
      isNew: false,
      formRules: {
        RECLOCK_DATE: [
          {
            required: true,
            message: '请选择补卡时间',
            trigger: 'change'
          },
        ],
        RECLOCK_REASON: [
          {
            required: true,
            message: '请输入补卡原因',
            trigger: 'change',
          },
        ],
        CHECK_ID: [
          {
            required: true,
            message: '请输入审批人',
            trigger: 'change',
          },
        ],
      },
      formOptions: {
        "CHECK_ID": departmentOptions.map(item => {
          if (item['部门'] == '测试') {
            if (apiConfig.baseUrl == 'cstApi/') {
              return {
                label: `${item['部门']}-${item['工号']}-${item['审批人']}`,
                value: `${item['工号']}`,
              };
            }
          }
          else {
            return {
              label: `${item['部门']}-${item['工号']}-${item['审批人']}`,
              value: `${item['工号']}`,
            };
          }
        }).filter(item => item),
        "STATE": [
          {
            type: 'info',
            text: '新建',
          },
          {
            type: '',
            text: '提交',
          },
          {
            type: 'success',
            text: '审批通过',
          },
          {
            type: 'danger',
            text: '审批不通过',
          },
          {
            type: 'success',
            text: '已完成',
          },
        ],
        "RECLOCK_REASON": [
          { id: 1, name: '漏打卡' },
          { id: 2, name: '公事外出' },
          { id: 3, name: '班车晚点' },
          { id: 4, name: '培训' },
          { id: 5, name: '会议' },
        ]
      },
      formItems: [
        {
          "value": "RECLOCK_DATE",
          "label": "未打卡时间",
          "isDate": true,
          "dateOption": {
            "type": "datetime",
            "format": "YYYY/MM/DD HH:mm",
            "dateFormat": "YYYY/MM/DD",
            "timeFormat": "HH:mm",
            "valueFormat": "YYYY/MM/DD HH:mm:ss",
          },
          "isEnableChange": true,
          "checkDisabledDate": function (date) {
            let now = dayjs(dialogDatas.currentData.CREATE_TIME).startOf('d');
            let dateRangeArr = [];
            //本周六，本周日，下周一，都可以补到本周三
            //本周二补到上周四，本周三补到上周五
            //本周四补到本周一，本周五补到本周二
            switch (now.day()) {
              case 1:
              case 2:
              case 3:
                dateRangeArr.push(now.add(-5, 'd'));
                break;
              case 4:
              case 5:
              case 6:
                dateRangeArr.push(now.add(-3, 'd'));
                break;
              case 0:
                dateRangeArr.push(now.add(-4, 'd'));
                break;
              default:
                dateRangeArr.push(now);
            }
            dateRangeArr.push(now);
            // date = dayjs(date);
            return date < dateRangeArr[0] || date > dateRangeArr[1];
            // return false;
          }
        },
        {
          "value": "RECLOCK_REASON",
          "label": "未打卡原因",
          "isDate": false,
          "handleGameSearch": (queryString, cb) => {
            const reasons = dialogDatas.formOptions.RECLOCK_REASON;
            const results = reasons.filter(item => {
              return item.name.includes(queryString);
            });
            cb(results.map(item => { return { value: item.name }; }));
          }
        },
        {
          "value": "CHECK_ID",
          "label": "审批人",
          "isDate": false,
          "isSelect": true,
          "isDisabled": true,
        },
      ],
      confirmBtnClick: function (state) {
        dialogFrom.value.validate((valid, fields) => {
          if (valid) {
            console.log('valid :>> ', valid);
            loading.value = true;

            let currentData = dialogDatas.currentData;
            let params = `${currentData.CREATER_ID}\t${currentData.RECLOCK_DATE}\t${currentData.RECLOCK_REASON}`
              + `\t${currentData.CHECK_ID}\t${dayjs().format('YYYY/MM/DD HH:mm:ss')}\t${''}`
              + `\t${state}\t${''}\t${currentData.RETURN_REASON}`;
            console.log(params);

            myAxios.get('统计当月补卡次数', `${currentData.RECLOCK_DATE}\t${currentData.CREATER_ID}`).then(res => {
              console.log(res[0].MATCHING_COUNT);
              if (res[0].MATCHING_COUNT < 3) {
                myAxios.post('陈帅廷新增或修改智联补卡记录', params).then(res => {
                  if (res.includes('成功')) {
                    loading.value = false;
                    dialogDatas.dialogFormVisible = false;
                    ElMessage({
                      type: 'success',
                      message: '提交成功!' + res
                    });
                    getTableDatas();
                  }
                  else {
                    loading.value = false;
                    ElMessageBox({
                      title: '警告',
                      type: 'warning',
                      message: '更新失败res!' + res
                    });
                  }
                }).catch((err) => {
                  loading.value = false;
                  ElMessageBox({
                    title: '警告',
                    type: 'warning',
                    message: '更新失败err!' + err
                  });
                });

                if (state == 1) {
                  let url = 'http://smartds.haitian.com:9091/cher/zhilian_reclock/dist/index.html#/sp/neworedit';
                  myAxios.postToWeChat(currentData.CHECK_ID, '请审批', '您有新的补卡申请,请及时审批', url).then(res => {
                    console.log('res :>> ', res);
                  });
                }
              } else {
                ElMessageBox({
                  title: '警告',
                  type: 'warning',
                  message: '本月已提交3次!'
                });
              }

            }).catch((err) => {
              loading.value = false;
              ElMessageBox({
                title: '警告',
                type: 'warning',
                message: '获取数据失败err!' + err
              });
            });
          }
        });
      },
      cancelBtnClick: function () {

      }
    });

    let getTableDatas = function () {
      loading.value = true;
      let params = `${userid}\t\t${userid}`;

      myAxios.get('陈帅廷查询智联人员补卡审批人', `${userid}`, '9900').then(spRes => {
        if (spRes.length) {
          let SP_WORKID = spRes[0].SP_WORKID;
          let SP_NAME = spRes[0].SP_NAME;

          dialogDatas.oriData.SP_WORKID = SP_WORKID;
          dialogDatas.oriData.CHECK_ID = SP_WORKID;
          dialogDatas.oriData.SP_NAME = SP_NAME;
          myAxios.get('陈帅廷查询智联补卡记录', params).then(res => {
            if (res instanceof Array) {
              loading.value = false;
              res.forEach(item => {
                item.SP_WORKID = SP_WORKID;
                item.SP_NAME = SP_NAME;
              });
              tableDatas.oritableData = [...res];
              // ElMessage({
              //   type: 'success',
              //   message: '最新数据获取成功!'
              // });
            }
            else {
              loading.value = false;
              ElMessageBox({
                title: '警告',
                type: 'warning',
                message: '获取数据失败res!' + res
              });
            }
          }).catch((err) => {
            loading.value = false;
            ElMessageBox({
              title: '警告',
              type: 'warning',
              message: '获取数据失败err!' + err
            });
          });
        }
        else {
          loading.value = false;
          ElMessageBox({
            title: '警告',
            type: 'warning',
            message: '未获取到您的审批人!'
          });
        }

      });

    };

    onMounted(() => {
      getTableDatas();
    });

    let tableDatas = reactive({
      //表格筛选展示相关代码
      filters: {

        //表格翻页相关代码
        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableDatasAfterFilter: computed(() => {
        let fData = tableDatas.oritableData;
        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;
        fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),

      tableColumns: [
        {
          "prop": "USERNAME",
          "label": "申请人",
          "align": "center"
        },
        {
          "prop": "RECLOCK_DATE",
          "label": "补卡日期",
          "align": "center"
        },
        {
          "prop": "RECLOCK_REASON",
          "label": "未打卡原因",
          "align": "center"
        },
        {
          "prop": "CHECK_ID",
          "label": "审批人工号",
          "align": "center"
        },
        {
          "prop": "CREATE_TIME",
          "label": "创建时间",
          "align": "center"
        },
        {
          "prop": "STATE",
          "label": "状态",
          "align": "center",
          "width": 110
        },
        {
          "prop": "GD_TIME",
          "label": "补卡时间",
          "align": "center",
        },
        {
          "prop": "RETURN_REASON",
          "label": "退回原因",
          "align": "center"
        },
        {
          "prop": "operate",
          "label": "操作",
          "align": "center",
          "width": 170
        }
      ],
      oritableData: [],
      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;

        let params = `${row.CREATER_ID}\t${row.RECLOCK_DATE}`;
        myAxios.post('陈帅廷删除智联补卡记录', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              type: 'success',
              message: '删除成功!' + res
            });
            tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
          }
          else {
            loading.value = false;
            ElMessageBox({
              title: '警告',
              type: 'warning',
              message: '删除失败res!' + res
            });
          }
        }).catch((err) => {
          loading.value = false;
          ElMessageBox({
            title: '警告',
            type: 'warning',
            message: '删除失败err!' + err
          });
        });

      },
      checkBtnClick: function (row) {
        loading.value = true;

        let params = `${row.CREATER_ID}\t${row.RECLOCK_DATE}\t${row.RECLOCK_REASON}`
          + `\t${row.CHECK_ID}\t${row.CREATE_TIME}\t${dayjs().format('YYYY/MM/DD HH:mm:ss')}`
          + `\t${2}\t${''}\t${row.RETURN_REASON}`;

        myAxios.post('陈帅廷新增或修改智联补卡记录', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              type: 'success',
              message: '操作成功!' + res
            });
            getTableDatas();
          }
          else {
            loading.value = false;
            ElMessageBox({
              title: '警告',
              type: 'warning',
              message: '操作失败res!' + res
            });
          }
        }).catch((err) => {
          loading.value = false;
          ElMessageBox({
            title: '警告',
            type: 'warning',
            message: '操作失败err!' + err
          });
        });

        let url = 'http://smartds.haitian.com:9091/cher/zhilian_reclock/dist/index.html#/home/homeSPTG';
        myAxios.postToWeChat('12822', '请补卡', '您有新的补卡申请,请及时补卡', url).then(res => {
          console.log('res :>> ', res);
        });
      },
      returnBtnClick: function (row) {
        ElMessageBox.prompt('请输入取消原因', '请输入', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          loading.value = true;
          let now = dayjs().format('YYYY/MM/DD HH:mm:ss');
          let params = `${row.CREATER_ID}\t${row.RECLOCK_DATE}\t${row.RECLOCK_REASON}`
            + `\t${row.CHECK_ID}\t${row.CREATE_TIME}\t${dayjs().format('YYYY/MM/DD HH:mm:ss')}`
            + `\t${3}\t${''}\t${now + ':' + value}`;

          myAxios.post('陈帅廷新增或修改智联补卡记录', params).then(res => {
            if (res.includes('成功')) {
              loading.value = false;
              dialogDatas.dialogFormVisible = false;
              ElMessage({
                type: 'success',
                message: '操作成功!' + res
              });
              getTableDatas();
            }
            else {
              loading.value = false;
              ElMessageBox({
                title: '警告',
                type: 'warning',
                message: '操作失败res!' + res
              });
            }
          }).catch((err) => {
            loading.value = false;
            ElMessageBox({
              title: '警告',
              type: 'warning',
              message: '操作失败err!' + err
            });
          });
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消',
          });
        });
      }
    });

    return {
      userid,
      departmentOptions,
      loading,
      addBtnClick,
      dialogFrom,
      dialogDatas,
      tableDatas,
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
</style>

